﻿using System.Collections;
using RAP.Framework.Libary.Utils;
using System.Xml;
using System.Collections.Generic;

namespace RAP.Framework.Libary.ServerCacheManager.CacheProxy
{
  /// <summary>
  /// 缓存代理基类
  /// </summary>
  public class CacheProxyBase : CacheObjectBase, ICacheProxy
  {
    public CacheProxyBase(string name = null)
        : base(name)
    {
    }

    /// <summary>
    /// 当前缓存代理是否有效
    /// </summary>
    public bool Enable { get; set; }

    /// <summary>
    /// 获取缓存实体的容器
    /// </summary>
    public virtual IDictionary ServerCache
    {
      get { return null; }
    }

    public IDictionary Configs { get; protected set; }

    public virtual void Initialize(IDictionary configs)
    {
      this.Configs = configs;
    }

    /// <summary>
    /// 获取指定Key的缓存实体
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public virtual IDictionary GetCacheObject(CacheKey key)
    {
      object cacheObj = null;
      var objectKey = key.ObjectKey.IsNullOrEmptyValue(key.ProxyKey);
      if (!this.ServerCache.Contains(objectKey))
      {
        lock (this.ServerCache)
        {
          if (!this.ServerCache.Contains(objectKey))
          {
            this.ServerCache[objectKey] = cacheObj = this.CreateCacheObject(objectKey);
            this.fireCacheAddedEvent(objectKey, cacheObj);
            (cacheObj as ICacheEvent).OnErrorEvent += CacheObject_OnError;
          }
        }
      }
      else
      {
        cacheObj = this.ServerCache[objectKey];
      }
      return cacheObj as IDictionary;
    }

    private void CacheObject_OnError(IDictionary exc)
    {
      this.fireErrorEvent(exc);
    }

    public virtual IDictionary GetCacheObject(string key)
    {
      return this.GetCacheObject(CacheKey.Create(key));
    }

    /// <summary>
    /// 创建指定名称的缓存对象
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    protected virtual IDictionary CreateCacheObject(string key)
    {
      return null;
    }

    /// <summary>
    /// 清除所有缓存实体
    /// </summary>
    public virtual void Clear()
    {
      foreach (object obj in this.ServerCache.Values)
      {
        IDictionary dict = obj as IDictionary;
        if (dict != null)
        {
          dict.Clear();
        }
      }
      this.fireCacheClearedEvent();
    }

    /// <summary>
    /// 移除指定Key的缓存实体
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public virtual bool RemoveCacheObject(string key)
    {
      if (this.ServerCache != null)
      {
        if (this.ServerCache.Contains(key))
        {
          object value = this.ServerCache[key];
          this.ServerCache.Remove(key);
          this.fireCacheRemovedEvent(key, value);
          return true;
        }
      }
      return false;
    }

  }
}
